app.controller("homeCtrl", function ($scope, $rootScope, $http, $state) {
    $rootScope.activeNavbar = Class.getConstant('NAVBAR_HOME');
    $scope.deleteDisabled = true;//删除按钮设置为不可点击
    $state.go(getSidebarReloadUrl($rootScope.activeSidebar));
    //请求用户数据
    $http({
        method: "GET",
        url: $rootScope.rootUrl + "/home/showUser",
        params: {}
    }).then(function (data) {
        $scope.userList = data.data.resultMap.data;
    });

    //刷新图片列表
    $scope.refreshHomeAdImgList = function () {
        var url = $rootScope.rootUrl + "/home/GetHomeAdImgList.do";
        $http({method: "POST", url: url}).then(function (data) {
            console.log(data);
            $scope.homeAdList = data.data.resultMap.data;
        });
    };
    $scope.refreshHomeAdImgList();

    var callback = function (data) {
        $scope.resultData = data;
    };

    //注册用户
    $scope.register = function () {
        var url = $rootScope.rootUrl + "/home/register";
        var jsonobj = {Name: "gubojun", Pass: "324234"};
        $http({method: "POST", url: url, data: jsonobj}).then(callback);
    };
    //显示用户
    $scope.showUser = function () {
        var url = $rootScope.rootUrl + "/home/showUser";
        $http({method: "POST", url: url}).then(callback);
    };
    //上传图片
    $scope.upload = function () {
        console.log("upload");
        var fd = new FormData();
        var file = document.querySelector('input[type=file]').files[0];
        var url = $rootScope.rootUrl + "/home/upload";
        fd.append('ImgData', file);
        $http({
            method: 'POST',
            url: url,
            data: fd,
            headers: {'Content-Type': undefined},
            transformRequest: angular.identity
        }).success(function (data) {
            //上传成功的操作
            alert("uplaod success");
            $scope.resultData = data.data;
        });
    };
    //导入图片
    $scope.saveClick = function () {
        //禁用按钮
        $scope.imgDisabled = true;
        $scope.submitDisabled = true;
        var url = $rootScope.rootUrl + Http.UploadHomeAdImg;//接口路径
        var fd = new FormData();
        // var file = document.querySelector('input[type=file]').files[0];
        if ($scope.file) {
            console.log($scope.file[0]);
        } else {
            alert('$scope.file 为空！');
            return;
        }
        fd.append($scope.file[0].name, $scope.file[0]);//参数 testReport=后台定义上传字段名称 ； $scope.file[0] 内容
        $http.post(url, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        }).success(function (data) {
            console.log(data);
            if (data.status != 1000) {
                alert(JSON.stringify('文件导入失败：' + $scope.file[0].name + '，请重新上传正确的文件或格式'));
            } else {
                $scope.refreshHomeAdImgList();
                alert(JSON.stringify('文件导入成功：' + $scope.file[0].name));
            }
            //恢复按钮
            $scope.imgDisabled = false;
            $scope.submitDisabled = false;
        }).error(function (data) {
            alert('服务器错误，文件导入失败！');
            //恢复按钮
            $scope.imgDisabled = false;
            $scope.submitDisabled = false;
        });
    };

    $scope.deleteImg = function () {
        var url = $rootScope.rootUrl + Http.DeleteImgByName;
        var jsonobj = {Name: $scope.imgName};
        $http.post(url, jsonobj).success(function (data) {
            console.log(data);
            if (data.status == 1000) {
                $scope.refreshHomeAdImgList();
                alert('文件删除成功');
                $scope.thumb = {imgSrc: null};
            } else {
                alert('文件删除失败,' + data.desc);
            }
            //恢复按钮
            $scope.imgDisabled = false;
            $scope.submitDisabled = false;
            $scope.deleteDisabled = true;
        }).error(function (data) {
            alert('服务器错误，文件删除失败！');
            //恢复按钮
            $scope.imgDisabled = false;
            $scope.submitDisabled = false;
        });
    };

    $scope.editImg = function (imgUrl, imgName) {
        $scope.imgName = imgName;
        $scope.deleteDisabled = false;
        $scope.fileName = imgName;
        $scope.thumb = {imgSrc: $rootScope.rootUrl + "/" + imgUrl + "/" + imgName};
    };
});

function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, img.width, img.height);
    var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
    var dataURL = canvas.toDataURL("image/" + ext);
    return dataURL;
}

//定义“上传”指令，修改后也可用于上传其他类型的文件
app.directive("imgUpload", function () {
    return {
        //通过设置项来定义
        restrict: 'AE',
        scope: false,
        template: '<div class="fl"><input type="button" id="storeBtn" style="padding:0; position: absolute; top: 0; left: 0; background: none; border: none;color: #fff; width:84px; height: 34px; line-height: 34px;" value="选择文件"><input type="file" name="testReport" id="file" ng-disabled="imgDisabled" style="position: absolute; top: 0; left: 0; opacity: 0; width:84px; height: 34px;" accept=".jpg,.png,.webp"></div>', //name:testReport 与接口字段相对应。
        replace: true,
        link: function (scope, ele, attrs) {
            ele.bind('click', function () {
                console.log("imgUpload click");
                $('#file').val('');
            });
            ele.bind('change', function () {
                console.log("imgUpload change");
                scope.file = ele[0].children[1].files;
                if (scope.file[0].size > 52428800) {
                    alert("图片大小不大于50M");
                    scope.file = null;
                    return false;
                }
                scope.fileName = scope.file[0].name;
                var postfix = scope.fileName.substring(scope.fileName.lastIndexOf(".") + 1).toLowerCase();
                if (postfix != "jpg" && postfix != "png"&& postfix != "webp") {
                    alert("图片仅支持png、jpg、webp类型的文件");
                    scope.fileName = "";
                    scope.file = null;
                    scope.$apply();
                    return false;
                }
                scope.$apply();
                scope.reader = new FileReader(); //创建一个FileReader接口
                console.log(scope.reader);
                console.log(scope.file);
                if (scope.file) {
                    //获取图片（预览图片）
                    scope.reader.readAsDataURL(scope.file[0]); //FileReader的方法，把图片转成base64
                    scope.reader.onload = function (ev) {
                        scope.$apply(function () {
                            scope.thumb = {
                                imgSrc: ev.target.result  //接收base64，scope.thumb.imgSrc为图片。
                            };
                        });
                    };
                } else {
                    alert('上传图片不能为空!');
                }
            });
        }
    };
});